package com.cty.biopool;

import com.cty.utils.Gen;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Auther: cty
 * @Date: 2020/4/16 23:52
 * @Description: BIO客户端
 * BIO Blocking IO 同步阻塞的编程方式
 * @version: 1.0
 */
public class PoolClient {
    public static void main(String[] args) {

        String host = Gen.genHost(args);
        int port = Gen.genPort(args);
        Socket client = null;
        BufferedReader reader = null;
        PrintWriter writer = null;
        Scanner scanner = new Scanner(System.in);
        String message = null;

        try {
            // 1 与服务端建立连接
            client = new Socket(host, port);
            System.out.println("Client started and connected the Server!");

            // 2 获取连接IO，并选择合适的流
            reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
            writer = new PrintWriter(new BufferedOutputStream(client.getOutputStream()),true);

            // 3 操作连接数据流
            while(true){
                // 获取控制台输入
                System.out.print("Client: ");
                message = scanner.nextLine();  // 【阻塞方法】

                // 若控制台输入“exit”，退出客户端
                if(message.equals("exit")){
                    System.out.println("Client exit!");
                    break;
                }

                // 将控制台输入发送到服务器端
                writer.println(message);
                writer.flush();

                // 读取服务器端的数据
                System.out.println(reader.readLine());  // 【阻塞方法】
            }


        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("Connection reset!");
        }
    }
}
